package com.lancoo.klgcourseware.manager;

import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.media.MediaPlayer;
import android.os.Build;
import android.os.Bundle;
import android.os.Looper;
import android.text.Html;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewParent;
import android.view.ViewStub;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.core.widget.NestedScrollView;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;

import com.bumptech.glide.Glide;
import com.bumptech.glide.request.target.SimpleTarget;
import com.bumptech.glide.request.transition.Transition;
import com.google.gson.Gson;
import com.lancoo.klgcourseware.R;
import com.lancoo.klgcourseware.entity.bean.KlgCardDialogConfigBean;
import com.lancoo.klgcourseware.entity.bean.KlgCommonBean;
import com.lancoo.klgcourseware.entity.bean.KlgDbConstant;
import com.lancoo.klgcourseware.ui.activity.KlgCourseWareMainActivity;
import com.lancoo.klgcourseware.ui.widget.VolumeAlignImageSpan;
import com.lancoo.klgcourseware.utils.KlgToolUtils;
import com.lancoo.klgcourseware.utils.KlgUrlEncodeUtils;
import com.lancoo.klgcourseware.utils.klog.KLog;

import java.util.List;

/**
 * Created by pengmi on 2020/12/15 14:48
 * Description:
 */
public class KlgCardDialogFragment extends DialogFragment implements View.OnClickListener{

    private View inflate;
    private long time;
    private int dissMissType,currentKlgIndex;

    private final static String KEY_SAVE_FLAG="isSave";
    private final static String KEY_CONFIG_FALG="KlgCardDialogConfigBean";
    private static final String TAG = "KlgCardDialogFragment";
    private ImageView img_senPhonetic;
    private ImageView img_usPhonetic;
    private ImageView img_unPhonetic;
    private TextView tv_explain;
    private ImageView img_arrorLeft;
    private ImageView img_arrorRight;
    private LinearLayout ll_unPhonetic;
    private TextView tv_sentenceStructures;
    private RelativeLayout ll_sentenceStructures;
    private VolumeAlignImageSpan centerAlignImageSpan;


    private boolean isRetractCard,hasSave,hasCustomBtn,hasNote;
    private String customBtnName,systemID;
    private List<KlgCommonBean> klgCommonBeanList;
    private KlgCommonBean commonBean;
    private KlgMediaManager klgMediaManager;
    private KlgCardDialogManager.KlgCardDismissListener listener;
    private int userType;


    public static void launchKlgCardDialogFragment(FragmentManager fragmentManager,KlgCardDialogConfigBean ben){
        launchKlgCardDialogFragment(fragmentManager,ben,null);
    }



    public static KlgCardDialogFragment launchKlgCardDialogFragment(FragmentManager fragmentManager,KlgCardDialogConfigBean ben,KlgCardDialogManager.KlgCardDismissListener listener){
        if(fragmentManager==null){
            return null;
        }
        String tag="KlgCardDialogFragment"+System.currentTimeMillis();
        if(ben!=null&&ben.getKlgCommonBeanList()!=null&&ben.getKlgCommonBeanList().size()>0
                &&ben.getKlgCommonBeanList().get(0)!=null){
            KlgCardDialogFragment fragment=new KlgCardDialogFragment();
            Bundle mBundle=new Bundle();
            mBundle.putSerializable(KEY_CONFIG_FALG,ben);
            mBundle.putBoolean(KEY_SAVE_FLAG,ben.isHasSave());
            Log.e("pmmmm","launchKlgCardDialogFragment hasSave:"+ben.isHasSave());
            mBundle.putString("tag",tag);
            fragment.setArguments(mBundle);
            try{
                fragment.setKlgCardDismissListener(listener);
                fragment.show(fragmentManager,tag);
                return fragment;
            }catch (Exception e){
                e.printStackTrace();
            }
        }else{
            KlgCardNoDataDialogFragment fragment=new KlgCardNoDataDialogFragment();
            try{
                fragment.show(fragmentManager,tag);
            }catch (Exception e){
                e.printStackTrace();
            }
        }
        return null;

    }

    private void setKlgCardDismissListener(KlgCardDialogManager.KlgCardDismissListener listener){
        this.listener=listener;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setStyle(DialogFragment.STYLE_NORMAL, R.style.klg_NoBgColorStyle);
    }


    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
//        getDialog().getWindow().getAttributes().windowAnimations = R.style.new_DialogAnimation;
    }

    @Override
    public void onStart() {
        super.onStart();
        Dialog dialog = getDialog();
        if (getArguments()!=null&&getContext()!=null&&dialog != null&& getActivity()!=null&&dialog.getWindow()!=null) {
            int screenWidth= KlgToolUtils.getWidthInPx(getContext());
            int width;
            int height;
            int imgHeight=KlgToolUtils.dip2px(getContext(),50);
            boolean hasSave=getArguments().getBoolean(KEY_SAVE_FLAG);
            Log.e("pmmm","hasSave:"+hasSave);
            if(KlgToolUtils.isPad(getContext())){
                width=KlgToolUtils.dip2px(getContext(),1395/3);
                height=KlgToolUtils.dip2px(getContext(),1000/3)+(hasSave?imgHeight:0);
                if(screenWidth<=width){
                    width=screenWidth;
                }
            }else{
                width=KlgToolUtils.dip2px(getContext(),953/3)*1092/953;
                height=KlgToolUtils.dip2px(getContext(),953/3)+(hasSave?imgHeight:0);
                if(screenWidth<=width){
                    width=screenWidth;
                }
            }
            dialog.getWindow().setLayout(width, height);
            dialog.getWindow().setGravity(Gravity.CENTER);
        }
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if(getArguments()!=null){
            KlgCardDialogConfigBean bean= (KlgCardDialogConfigBean) getArguments().getSerializable(KEY_CONFIG_FALG);
            if(bean!=null){
                klgCommonBeanList=bean.getKlgCommonBeanList();
                commonBean = klgCommonBeanList.get(currentKlgIndex);
                isRetractCard=bean.isRetractCard();
                hasSave=bean.isHasSave();
                hasCustomBtn=bean.isHasCustomBtn();
                hasNote=bean.isHasNote();
                customBtnName=bean.getCustomBtnName();
                systemID=bean.getSystemID();
                userType=bean.getUserType();
            }
        }
        inflate = inflater.inflate(R.layout.klg_dialog_card_word,container,false);
        initView(inflate);
        return inflate;
    }
    
    private void initView(View inflate){
        RelativeLayout rl_head = inflate.findViewById(R.id.rl_head);
        ViewGroup.LayoutParams layoutParams = rl_head.getLayoutParams();
        if(KlgToolUtils.isPad(getContext())){
            layoutParams.height=KlgToolUtils.dip2px(getContext(),1202/3)*65/300;
        }else{
            layoutParams.height=KlgToolUtils.dip2px(getContext(),953/3)*76/280;
        }
        rl_head.setLayoutParams(layoutParams);
        LinearLayout ll_bottom = inflate.findViewById(R.id.ll_bottom);
        ViewGroup.LayoutParams layoutParams2 = ll_bottom.getLayoutParams();

        if(KlgToolUtils.isPad(getContext())){
            layoutParams2.height=KlgToolUtils.dip2px(getContext(),1202/3)*35/300;
        }else{
            layoutParams2.height=KlgToolUtils.dip2px(getContext(),953/3)*38/280;
        }
        ll_bottom.setLayoutParams(layoutParams2);
        NestedScrollView nestedScrollView = inflate.findViewById(R.id.scroll_view);
        ViewGroup.LayoutParams layoutParams3 =nestedScrollView.getLayoutParams();
        if(KlgToolUtils.isPad(getContext())){
            layoutParams3.height=KlgToolUtils.dip2px(getContext(),1202/3)*117/300;
        }else{
            layoutParams3.height=KlgToolUtils.dip2px(getContext(),953/3)*(140)/280;
        }
        nestedScrollView.setLayoutParams(layoutParams3);
        showFayinStyle(getContext(),commonBean, inflate,isRetractCard);
        showWordMoreMessageStyle(getContext(),commonBean, inflate,isRetractCard);
        showFayinViewStyle(getContext(), inflate);
        showWordMsgViewStyle(getContext(), inflate);
        View view = inflate.findViewById(R.id.ll_klg_card);
        view.setBackgroundResource(isRetractCard||hasSave?R.drawable.klg_icon_klg_card_no_close_bg:R.drawable.klg_icon_klg_card_bg);
        TextView tv_retractCard = inflate  .findViewById(R.id.tv_retract_card);
        img_arrorLeft = inflate.findViewById(R.id.img_arror_left);
        img_arrorRight = inflate.findViewById(R.id.img_arror_right);
        img_arrorLeft.setOnClickListener(this);
        img_arrorRight.setOnClickListener(this);
        if(klgCommonBeanList!=null&&klgCommonBeanList.size()>1){
            img_arrorRight.setVisibility(View.VISIBLE);
        }
        tv_retractCard.setText(isRetractCard?R.string.klg_retract_card:(userType==1?R.string.klg_explain_details:R.string.klg_study_strength));
        if(commonBean.isHideBtn()&&TextUtils.isEmpty(commonBean.getUs_voice())&&
                TextUtils.isEmpty(commonBean.getUn_voice())&&
                TextUtils.isEmpty(commonBean.getUs_phonetic())&&
                TextUtils.isEmpty(commonBean.getUn_phonetic())){
            tv_retractCard.setVisibility(View.GONE);
            inflate.findViewById(R.id.view_divider_right).setVisibility(View.GONE);
        }else{
            tv_retractCard.setVisibility(View.VISIBLE);
            inflate.findViewById(R.id.view_divider_right).setVisibility(View.VISIBLE);
        }
        tv_retractCard.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(isRetractCard?
                R.mipmap.klg_icon_retract_card:R.mipmap.klg_icon_entry_courseware),null,null,null);
        inflate.findViewById(R.id.img_close).setEnabled(!(isRetractCard||hasSave));
        inflate.findViewById(R.id.img_close).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(System.currentTimeMillis()-time<500){
                    return;
                }
                time=System.currentTimeMillis();
                dissMissType=0;
                dismissAllowingStateLoss();
//                if(klgCardDialog !=null&&klgCardDialog.get()!=null&& klgCardDialog.get().isShowing()){
//                    klgCardDialog.get().dismiss();
//                }

            }
        });
        Log.e("123123","hasCustomBtn:"+hasCustomBtn+"hasSave:"+hasSave+"hasNote:"+hasNote);
        if(hasCustomBtn||hasSave||hasNote){
            inflate.findViewById(R.id.view_add_restudy_weight).setVisibility(View.VISIBLE);
            TextView tv_addStudy = inflate.findViewById(R.id.tv_add_study);
            if(!TextUtils.isEmpty(customBtnName)){
                ((TextView)inflate.findViewById(R.id.tv_add_study)).setText(customBtnName);
            }else{
                if(hasNote){
                    tv_addStudy.setText(R.string.klg_make_note);
                    tv_addStudy.setCompoundDrawablesWithIntrinsicBounds(getContext().getResources().getDrawable(R.mipmap.klg_icon_make_note),null,null,null);
                }
                final String tag=getArguments().getString("tag");
                if(hasSave){
                    final ImageView img_save=inflate.findViewById(R.id.img_save);
                    img_save.setVisibility(View.VISIBLE);
                    img_save.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            if(System.currentTimeMillis()-time<500){
                                return;
                            }
                            time=System.currentTimeMillis();
                            dissMissType=-1;
                            if(listener!=null){
                                if(klgCommonBeanList!=null&&currentKlgIndex<klgCommonBeanList.size()){
                                    listener.onCardDismiss(3,currentKlgIndex,klgCommonBeanList.get(currentKlgIndex),tag);
                                }else{
                                    listener.onCardDismiss(3,currentKlgIndex,commonBean,tag);
                                }
                            }
                        }
                    });
                    img_save.setImageResource(commonBean.getIsCollectWord()==0?R.mipmap.klg_icon_save_white:
                            R.mipmap.klg_icon_save_blue);
                    inflate.findViewById(R.id.img_close_x).setOnClickListener(this);
                    inflate.findViewById(R.id.img_close_x).setVisibility(View.VISIBLE);
                    TextView tv_klgName = inflate.findViewById(R.id.tv_klg_name);
                    RelativeLayout.LayoutParams lp_klgName = (RelativeLayout.LayoutParams) tv_klgName.getLayoutParams();
                    lp_klgName.addRule(RelativeLayout.ALIGN_PARENT_LEFT);
                    lp_klgName.addRule(RelativeLayout.LEFT_OF,R.id.img_save);
                }
            }
            inflate.findViewById(R.id.tv_add_study).setVisibility(View.VISIBLE);
            inflate.findViewById(R.id.tv_add_study).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if(System.currentTimeMillis()-time<500){
                        return;
                    }
                    time=System.currentTimeMillis();
                    dissMissType=1;
                    dismissAllowingStateLoss();
//                    if(klgCardDialog !=null&&klgCardDialog.get()!=null&& klgCardDialog.get().isShowing()){
//                        klgCardDialog.get().dismiss();
//                    }
//                    if(mCustomBtnClickListener!=null){
//                        mCustomBtnClickListener.onCustomBtnClick(commonBean,v);
//                    }
                }
            });
        }
        controlImgAnimation(false,false,false);
    }

    /**
     * @param mContext
     * @param klgCommonBean
     * @param convertView
     * @param isRetractCard
     */
    private void showFayinStyle(final Context mContext, final KlgCommonBean klgCommonBean, View convertView,final boolean isRetractCard){
        TextView tv_klgName = inflate.findViewById(R.id.tv_klg_name);
        tv_klgName.setText(klgCommonBean.getKlgName());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            tv_klgName.setLetterSpacing(0.04f);
        }
        //知识点发音
        if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUs_phonetic())&&
                TextUtils.isEmpty(klgCommonBean.getUn_voice())&&TextUtils.isEmpty(klgCommonBean.getUs_voice())){
            convertView.findViewById(R.id.ll_fayin).setVisibility(View.GONE);
        }else{
            convertView.findViewById(R.id.ll_fayin).setVisibility(View.VISIBLE);
            if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                convertView.findViewById(R.id.ll_un_phonetic).setVisibility(View.GONE);
            }else{
                convertView.findViewById(R.id.ll_un_phonetic).setVisibility(View.VISIBLE);
                TextView tv_unPhonetic = convertView.findViewById(R.id.tv_un_phonetic);
                try{
                    Typeface typeFace = Typeface.createFromAsset(mContext.getAssets(), "klg_droid_sans_bold.ttf");
                    tv_unPhonetic.setTypeface(typeFace);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if(TextUtils.isEmpty(klgCommonBean.getUn_phonetic())){
                    tv_unPhonetic.setText(mContext.getString(R.string.klg_un));
                }else{
                    tv_unPhonetic.setText(mContext.getString(R.string.klg_un)+" "+ klgCommonBean.getUn_phonetic());
                }

                if(!TextUtils.isEmpty(klgCommonBean.getUn_voice())){
                    convertView.findViewById(R.id.ll_un_phonetic).setTag(klgCommonBean.getUn_voice());
                    ll_unPhonetic = convertView.findViewById(R.id.ll_un_phonetic);
                    ll_unPhonetic.setOnClickListener(this);
                }else{
                    convertView.findViewById(R.id.img_un_phonetic).setVisibility(View.GONE);
                }
            }
            if(TextUtils.isEmpty(klgCommonBean.getUs_phonetic())&&TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                convertView.findViewById(R.id.ll_us_phonetic).setVisibility(View.GONE);
            }else{
                convertView.findViewById(R.id.ll_us_phonetic).setVisibility(View.VISIBLE);
                TextView tv_usPhonetic = convertView.findViewById(R.id.tv_us_phonetic);
                if(TextUtils.isEmpty(klgCommonBean.getUs_phonetic())){

                    tv_usPhonetic.setText(mContext.getString(R.string.klg_us));
//                        convertView.findViewById(R.id.tv_us_phonetic).setVisibility(View.GONE);
                }else{
                    tv_usPhonetic.setText(mContext.getString(R.string.klg_us)+" "+ klgCommonBean.getUs_phonetic());
                }
                try{
                    Typeface typeFace = Typeface.createFromAsset(mContext.getAssets(), "klg_droid_sans_bold.ttf");
                    tv_usPhonetic.setTypeface(typeFace);
                }catch (Exception e){
                    e.printStackTrace();
                }
                if(!TextUtils.isEmpty(klgCommonBean.getUs_voice())){
                    LinearLayout ll_usPhonetic = convertView.findViewById(R.id.ll_us_phonetic);
                    ll_usPhonetic.setTag(klgCommonBean.getUs_voice());
                    ll_usPhonetic.setOnClickListener(this);
                }else{
                    convertView.findViewById(R.id.img_us_phonetic).setVisibility(View.GONE);
                }
            }
        }
        TextView tv_retractCard = convertView.findViewById(R.id.tv_retract_card);
        tv_retractCard.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(System.currentTimeMillis()-time<500){
                    return;
                }
                time=System.currentTimeMillis();
                dissMissType=2;
//                if(klgCardDialog !=null&&klgCardDialog.get()!=null&& klgCardDialog.get().isShowing()){
//                    klgCardDialog.get().dismiss();
//                }
                dismissAllowingStateLoss();
                if(!isRetractCard){//进入知识点学习课件。。。
                    if(KlgCourseWareManager.getVipLimitState(mContext)){
                        KlgCourseWareManager. showTrainAgainDialog();
                        return;
                    }
                    String klgCode=TextUtils.isEmpty(klgCommonBean.getOldKlgCode())?klgCommonBean.getKlgCode():klgCommonBean.getOldKlgCode();
                    KlgCourseWareMainActivity.launch(getActivity(),klgCode,true);
                }
            }
        });
    }

    private void showWordMoreMessageStyle(final Context mContext,KlgCommonBean klgCommonBean,View convertView,final boolean isRetractCard){
        //知识点释义
        if(klgCommonBean.getExplain()==null||TextUtils.isEmpty(klgCommonBean.getExplain())||TextUtils.equals("null",klgCommonBean.getExplain())){
            convertView.findViewById(R.id.tv_meaning_explain).setVisibility(View.GONE);
            convertView.findViewById(R.id.tv_meaning).setVisibility(View.GONE);
        }else {
            Log.e("aaaaaa","释义："+klgCommonBean.getExplain());
            tv_explain = convertView.findViewById(R.id.tv_meaning);
            tv_explain.setVisibility(View.VISIBLE);
            tv_explain.setText(Html.fromHtml(klgCommonBean.getExplain()));
            if(klgCommonBean.isShowMoreMeaning()&&!TextUtils.isEmpty(klgCommonBean.getShortExplan())){
                tv_explain.setText(klgCommonBean.getShortExplan());
                convertView.findViewById(R.id.tv_more).setVisibility(View.VISIBLE);
                convertView.findViewById(R.id.tv_more).setTag(klgCommonBean.getExplain());
                convertView.findViewById(R.id.tv_more).setOnClickListener(this);
            }else {
                tv_explain.setText(Html.fromHtml(klgCommonBean.getExplain()));
                convertView.findViewById(R.id.tv_more).setVisibility(View.GONE);
            }

        }
        //句型
        if(klgCommonBean.getParaphrase()==null||TextUtils.isEmpty(klgCommonBean.getParaphrase())||TextUtils.equals("null",klgCommonBean.getParaphrase())){
            convertView.findViewById(R.id.tv_sentence_pattern_explain).setVisibility(View.GONE);
            convertView.findViewById(R.id.tv_sentence_pattern).setVisibility(View.GONE);
        }else{
            Log.e("aaaaaa","句型："+klgCommonBean.getParaphrase());
            TextView tv_sentence = convertView.findViewById(R.id.tv_sentence_pattern);
            tv_sentence.setText(klgCommonBean.getParaphrase());
        }
        //用法
        if(TextUtils.isEmpty(klgCommonBean.getUsage())){

            convertView.findViewById(R.id.tv_usage_analysis_explain).setVisibility(View.GONE);
            convertView.findViewById(R.id.tv_usage_analysis).setVisibility(View.GONE);
        }else{
            Log.e("aaaaaa","用法："+klgCommonBean.getUsage());
            TextView tv_usageAnalysis = convertView.findViewById(R.id.tv_usage_analysis);
            tv_usageAnalysis.setText(Html.fromHtml(klgCommonBean.getUsage()));
        }
        //例句
        if(TextUtils.isEmpty(klgCommonBean.getClassicSen())){
            convertView.findViewById(R.id.tv_sentence_structures_explain).setVisibility(View.GONE);
            convertView.findViewById(R.id.ll_sentence_structures).setVisibility(View.GONE);
        }else{
            convertView.findViewById(R.id.ll_sentence_structures).setVisibility(View.VISIBLE);
            tv_sentenceStructures = convertView.findViewById(R.id.tv_sentence_structures);
            TextView tv_sentenceStructureChinese = convertView.findViewById(R.id.tv_sentence_structures_chinese);
            SpannableStringBuilder spannableStringBuilder=new SpannableStringBuilder();
            SpannableString ss_content=new SpannableString(Html.fromHtml(klgCommonBean.getClassicSen().replace("font color='#0077f0'","font color='#64a9d0'")));
            spannableStringBuilder.append(ss_content);
            tv_sentenceStructureChinese.setText(klgCommonBean.getClassicTrain());
            if(!TextUtils.isEmpty(klgCommonBean.getClassicVoice())){
                ll_sentenceStructures = convertView.findViewById(R.id.ll_sentence_structures);
                ll_sentenceStructures.setTag(klgCommonBean.getClassicVoice());
                convertView.findViewById(R.id.ll_sentence_structures).setOnClickListener(this);
                String imgSpanStr="  lpl";
                SpannableString ss_volume=new SpannableString(imgSpanStr);
                Bitmap bitmap = BitmapFactory.decodeResource(mContext.getResources(), R.drawable.klg_volume_cyan_4);
                if(centerAlignImageSpan==null){
                    centerAlignImageSpan = new VolumeAlignImageSpan(mContext,bitmap);
                }else{
                    centerAlignImageSpan.destoryVolumeImageSpan(tv_sentenceStructures);
                }
                ss_volume.setSpan(centerAlignImageSpan,imgSpanStr.length()-3,imgSpanStr.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                spannableStringBuilder.append(ss_volume);
//                SpannableString ss_end=new SpannableString("1");
//                ss_end.setSpan(new ForegroundColorSpan(Color.TRANSPARENT),0,1,Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
//                spannableStringBuilder.append(ss_end);
            }
            tv_sentenceStructures.setText(spannableStringBuilder);
        }
        if(TextUtils.equals("ESP",klgCommonBean.getKlgType())){
            inflate.findViewById(R.id.ll_sentence_structures).setVisibility(View.GONE);
            if(!TextUtils.isEmpty(klgCommonBean.getClassicSen())){
                ViewStub viewStub = inflate.findViewById(R.id.viewstub_train_picture);
                if(viewStub!=null){
                    viewStub.inflate();
                    inflate.findViewById(R.id.tv_picture_explain).setVisibility(View.GONE);
                    final ImageView img_picture = inflate.findViewById(R.id.img_picture);
//                    Glide.with(mContext).load(KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen()).into(img_picture);
                    String url;
                    if(klgCommonBean.getClassicSen().toLowerCase().startsWith("http")){
                        url=klgCommonBean.getClassicSen();
                    }else{
                        url=KlgDbConstant.mediaUrl+klgCommonBean.getClassicSen();
                    }
                    Glide.with(mContext).asBitmap().load(url)
                            .into(new SimpleTarget<Bitmap>() {
                                @Override
                                public void onResourceReady(@NonNull Bitmap resource, @Nullable Transition<? super Bitmap> transition) {
//                            resource.
                                    int width = resource.getWidth();//图片原始宽度
                                    int height = resource.getHeight();//图片原始高度
                                    int scaledW = KlgToolUtils.dip2px(mContext,180f);//固定图片展示高度为180dp
                                    int scaledH = (height * scaledW) /width ;//计算出按比缩放后的宽度
                                    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(scaledW, scaledH);
                                    img_picture.setLayoutParams(lp);
                                    img_picture.setImageBitmap(resource);

                                }
                            });
                }
                inflate.findViewById(R.id.img_picture).setVisibility(View.VISIBLE);
            }
        }else{
            if(inflate.findViewById(R.id.img_picture)!=null){
                inflate.findViewById(R.id.img_picture).setVisibility(View.GONE);
            }
        }
    }

    private void showFayinViewStyle(Context mContxt,View convertView){
        TextView tv_usPhoneTic = convertView.findViewById(R.id.tv_us_phonetic);
        TextView tv_unPhoneTic = convertView.findViewById(R.id.tv_un_phonetic);
        tv_unPhoneTic.setTextColor(Color.parseColor("#dce6fd"));
        tv_usPhoneTic.setTextColor(Color.parseColor("#dce6fd"));
        int fayinTextSize=KlgToolUtils.isPad(mContxt)?15:13;
        tv_unPhoneTic.setTextSize(fayinTextSize);
        tv_usPhoneTic.setTextSize(fayinTextSize);
        img_usPhonetic = convertView.findViewById(R.id.img_us_phonetic);
        img_unPhonetic = convertView.findViewById(R.id.img_un_phonetic);
        LinearLayout.LayoutParams layoutParams_unPhonetic = (LinearLayout.LayoutParams) img_unPhonetic.getLayoutParams();
        LinearLayout.LayoutParams layoutParams_usPhonetic = (LinearLayout.LayoutParams) img_usPhonetic.getLayoutParams();
        int dp5=KlgToolUtils.dip2px(mContxt,5);
        layoutParams_unPhonetic.rightMargin=dp5;
        layoutParams_usPhonetic.rightMargin=dp5;
        img_unPhonetic.setLayoutParams(layoutParams_unPhonetic);
        img_usPhonetic.setLayoutParams(layoutParams_usPhonetic);

    }

    private void showWordMsgViewStyle(Context mContext, View convertView){
        convertView.findViewById(R.id.tv_meaning_explain).setVisibility(View.GONE);
        convertView.findViewById(R.id.tv_sentence_pattern_explain).setVisibility(View.GONE);
        convertView.findViewById(R.id.tv_usage_analysis_explain).setVisibility(View.GONE);
        convertView.findViewById(R.id.tv_sentence_structures_explain).setVisibility(View.GONE);
        img_senPhonetic = convertView.findViewById(R.id.img_sentence_strutures);
        img_senPhonetic.setVisibility(View.GONE);
        int dp24=KlgToolUtils.dip2px(mContext,18);
        int dp6=KlgToolUtils.dip2px(mContext,6);
        int textSize=KlgToolUtils.isPad(mContext)?18:14;
        TextView tv_more = convertView.findViewById(R.id.tv_more);
        tv_more.setPadding(0,0,0,dp6);
        tv_more.setTextSize(textSize);
        TextView tv_meaning = convertView.findViewById(R.id.tv_meaning);
        tv_meaning.setPadding(0,dp24,0,tv_more.getVisibility()==View.VISIBLE?0:dp6);
        tv_meaning.setTextColor(Color.parseColor("#333333"));
        tv_meaning.setTextSize(textSize);
        TextView tv_sentencePattern = convertView.findViewById(R.id.tv_sentence_pattern);
        tv_sentencePattern.setPadding(0,dp24,0,dp6);
        tv_sentencePattern.setTextColor(Color.parseColor("#333333"));
        tv_sentencePattern.setTextSize(textSize);
        TextView tv_usageAnalysis =convertView.findViewById(R.id.tv_usage_analysis);
        tv_usageAnalysis.setPadding(0,dp24,0,dp6);
        tv_usageAnalysis.setTextColor(Color.parseColor("#333333"));
        tv_usageAnalysis.setTextSize(textSize);
        TextView tv_sentenceStructures =convertView.findViewById(R.id.tv_sentence_structures);
        tv_sentenceStructures.setTextColor(Color.parseColor("#333333"));
        tv_sentenceStructures.setTextSize(textSize);
        TextView tv_sentenceStructuresChinese =convertView.findViewById(R.id.tv_sentence_structures_chinese);
        tv_sentenceStructuresChinese.setTextColor(Color.parseColor("#575757"));
        tv_sentenceStructuresChinese.setTextSize(textSize);

        convertView.findViewById(R.id.ll_sentence_structures).setPadding(0,dp24,0,dp6);
        LinearLayout ll_wordMsgDetails = convertView.findViewById(R.id.ll_word_msg_details);
        int paddingDp = KlgToolUtils.dip2px(mContext, 10);
        ll_wordMsgDetails.setPadding(paddingDp,0,paddingDp*2,0);

    }

    private void updateCollectionState(Context mContext, KlgCommonBean commonBean, View inflate){
        ImageView img_save = inflate.findViewById(R.id.img_save);
        img_save.setImageResource(commonBean.getIsCollectWord()==1?R.mipmap.klg_icon_save_blue:R.mipmap.klg_icon_save_white);

        TextView tv_retract_card = inflate.findViewById(R.id.tv_retract_card);
        tv_retract_card.setVisibility(commonBean.isHideBtn()?View.GONE:View.VISIBLE);
        inflate.findViewById(R.id.view_divider_right).setVisibility(commonBean.isHideBtn()?View.GONE:View.VISIBLE);
    }

    @Override
    public void onClick(View view) {
        if(System.currentTimeMillis()-time<500){
            return;
        }
        time=System.currentTimeMillis();
        String brand = Build.BRAND;
        Log.e("aaaaaaa","brand:"+brand);
        int id=view.getId();
        if(id==R.id.ll_un_phonetic){//英式
            String url = (String) view.getTag();
            playSound(url,img_unPhonetic);
        }else if(id==R.id.ll_us_phonetic){//美式
            String url = (String) view.getTag();
            playSound(url,img_usPhonetic);
        }else if(id==R.id.ll_sentence_structures){//例句
            String url = (String) view.getTag();
            playSound(url,img_senPhonetic);
        }else if(id==R.id.tv_more){
            view.setVisibility(View.GONE);
            String explain = (String) view.getTag();
            if(tv_explain!=null&&tv_explain!=null){
                tv_explain.setText(explain);
            }
        }else if(id==R.id.img_arror_left){
            if(klgCommonBeanList==null){
                return;
            }
            if(currentKlgIndex==1){
                view.setVisibility(View.INVISIBLE);
            }
            if(img_arrorRight!=null){
                img_arrorRight.setVisibility(View.VISIBLE);
            }

            currentKlgIndex--;
            if(inflate!=null){
                showFayinStyle(view.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate,false);
                showWordMoreMessageStyle(view.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate,false);
                updateCollectionState(view.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate);
            }
            pause();
        }else if(id==R.id.img_arror_right){
            if(klgCommonBeanList==null){
                return;
            }
            if(currentKlgIndex==klgCommonBeanList.size()-2){
                view.setVisibility(View.INVISIBLE);
            }
            if(img_arrorLeft!=null){
                img_arrorLeft.setVisibility(View.VISIBLE);
            }
            currentKlgIndex++;
            if(inflate!=null){
                showFayinStyle(view.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate,false);
                showWordMoreMessageStyle(view.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate,false);
                updateCollectionState(view.getContext(),klgCommonBeanList.get(currentKlgIndex),inflate);
            }
            pause();
        }else if(id==R.id.img_save){//点击收藏

        }else if(id==R.id.img_close_x){//关闭
            dissMissType=0;
            dismissAllowingStateLoss();
        }
    }

    /**
     * 控制美式，英式，例句播放动画
     */
    private void controlImgAnimation(boolean isOpend,boolean isOpen1,boolean isOpend2){
        if(img_senPhonetic==null){
            return;
        }
        volumeAnimationControl(img_usPhonetic,isOpend);
        volumeAnimationControl(img_unPhonetic,isOpen1);
        volumeAnimationControl(img_senPhonetic,isOpend2);
        if(centerAlignImageSpan==null||tv_sentenceStructures==null||
                tv_sentenceStructures==null){
            return;
        }
        if(isOpend2){
            centerAlignImageSpan.startVolumeAnimation(tv_sentenceStructures);
        }else{
            centerAlignImageSpan.stopVolumeAnimation(tv_sentenceStructures);
        }
    }


    /**
     * 设置动画
     * @param img
     * @param isAnimation
     */
    protected void volumeAnimationControl(ImageView img, boolean isAnimation){
        if( Looper.myLooper() != Looper.getMainLooper()){
            return;
        }
        if(img!=null&&img.getVisibility()== View.VISIBLE){
            if(isAnimation){
//                img.setImageResource(R.drawable.lgklg_animation_list_volume_cyan);
                img.setBackground(null);
                ((AnimationDrawable)img.getDrawable()).start();
            }else{
//                img.setImageResource(R.drawable.lgklg_volume_cyan_3);
                ((AnimationDrawable)img.getDrawable()).stop();
                ((AnimationDrawable)img.getDrawable()).selectDrawable(0);
                img.setBackgroundResource(R.drawable.klg_volume_cyan_3);

            }
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        Log.e("eeee","onPause,"+TAG);
        pause();
    }

    @Override
    public void onDestroyView() {
        Log.e("eeee","onDestroyView,"+TAG);
        release();

        super.onDestroyView();
    }

    @Override
    public void onDismiss(@NonNull DialogInterface dialog) {
        dismissAllowingStateLoss();
        Log.e("eeee",dissMissType+"onDismiss,"+TAG+systemID);

        if(listener!=null){
            if(!TextUtils.isEmpty(systemID)&&dissMissType!=1){
                return;
            }
            if(klgCommonBeanList!=null&&currentKlgIndex<klgCommonBeanList.size()){
                listener.onCardDismiss(dissMissType,currentKlgIndex,klgCommonBeanList.get(currentKlgIndex),null);
            }else{
                listener.onCardDismiss(dissMissType,currentKlgIndex,commonBean,null);
            }
        }
        if(inflate!=null){
            inflate.findViewById(R.id.img_save).setOnClickListener(null);

        }
        if(inflate!=null){
            if(inflate.getParent()!=null){
                ViewParent parent = inflate.getParent();
                if(parent instanceof ViewGroup){
                    Log.e("eeee","去除inflate");
                    ((ViewGroup) parent).removeView(inflate);
                }

            }
            inflate=null;
        }

        super.onDismiss(dialog);
        if(getDialog()!=null){
            getDialog().setOnCancelListener(null);
        }

    }

    /**
     * 暂停
     */
    private void pause(){
        if(klgMediaManager!=null){
            klgMediaManager.pause();
        }
        controlImgAnimation(false,false,false);
    }

    /**
     * 销毁
     */
    public void release(){
        if(klgMediaManager!=null){
            klgMediaManager.release();
            klgMediaManager=null;
        }
        if(centerAlignImageSpan!=null&&tv_sentenceStructures!=null){
            centerAlignImageSpan.destoryVolumeImageSpan(tv_sentenceStructures);
        }
        if(listener!=null){
            listener=null;
        }

    }

    /**
     * 开启音频播放
     * @param url 音频url
     * @param img imgView
     */
    private void playSound(String url,final ImageView img){
//        url="https://lgresv57.obs.cn-south-1.myhuaweicloud.com/LGFTP/EspKnowledge/SpiderMaterial/English/Audio/G/20190323130325700.mp3";
        Log.e("aaaaa","playSound url:"+url);
        if(klgMediaManager==null){
            klgMediaManager = new KlgMediaManager(img.getContext());
        }
        controlImgAnimation(false,false,false);
        klgMediaManager.setUpMedia(KlgUrlEncodeUtils.urlencodChange(url), new KlgMediaManager.OnPlayListener() {

            @Override
            public void onComplete() {
                controlImgAnimation(false,false,false);
            }

            @Override
            public void onStartError() {
                controlImgAnimation(false,false,false);
            }

            @Override
            public void onPausePlay() {

            }

            @Override
            public void onSourceError() {
                controlImgAnimation(false,false,false);
            }

            @Override
            public void onResumePlay() {

            }

            @Override
            public void onStopPlay() {

            }

            @Override
            public void onPrepare() {
                if(klgMediaManager!=null){
                    klgMediaManager.start();
                }
                controlImgAnimation(img==img_usPhonetic,img==img_unPhonetic,img==img_senPhonetic);
            }

            @Override
            public void onBufferingUpdate(MediaPlayer mp, int percent) {

            }
        });
    }

    public void updateCollectionState(int state) {
        if(getContext()==null){
            return;
        }
        if(inflate!=null){
            ((ImageView)inflate.findViewById(R.id.img_save)).setImageResource(state==1?R.mipmap.klg_icon_save_blue:R.mipmap.klg_icon_save_white);
        }

    }



}
